<?php
namespace app\common\model;

use app\common\service\LangMap;
use think\facade\Db;
use think\model\concern\SoftDelete;
use think\Paginator;

class CommentModel extends BaseModel
{
    use SoftDelete;
    protected $table='comment';
    public static $state_fields = [
        'state_zs' => ['name'=>'按时送达'],
        'state_zy' => ['name'=>'技师专业'],
        'state_gds' => ['name'=>'高大上'],
        'state_tdh' => ['name'=>'态度好'],
        'state_lm' => ['name'=>'礼貌热情'],
        'state_xjb' => ['name'=>'性价比高'],
        'state_tyh' => ['name'=>'体验很棒'],
        'state_ynx' => ['name'=>'有耐心'],
    ];

    public static $fields_type = [
        ['name'=>'订单'],
    ];

    public function getImgAttr($value)
    {
        return empty($value) ? [] : explode(',' ,$value);
    }



    //订单评论详情
    public static function orderGoodsDetail(UserModel $user_model,array $input_data = [])
    {
        $order_id = $input_data['order_id']??0;
        $model_order = OrderModel::with(['linkUser'])->where(['uid'=>$user_model['id'],'id'=>$order_id])->find();
        $goods_list = [];
        OrderGoodsModel::where(['oid'=>$model_order['id']])->select()->each(function($item)use(&$goods_list){
            array_push($goods_list,$item->apiNormalInfo());
        });
        return [empty($model_order) ? [] : $model_order->apiNormalInfo(), $goods_list];
    }

    public static function goodsComment(array $input_data = [])
    {
        $content = trim($input_data['content']??'');
        $goods_id = $input_data['goods_id']??0;
        $user_id = $input_data['user_id']??0;
        $img = $input_data['img']??[];
        $public = $input_data['public']??2;
        $level = $input_data['level']??5;
        $logistics = $input_data['logistics']??5;
        $service = $input_data['service']??5;
        $praise = $input_data['praise']??5;

        if(empty($goods_id)) throw new \Exception('请输入商品id');
        if(empty($content)) throw new \Exception('请输入评论内容');
        $model = new self();
        $model->setAttrs([
            'content' => $content,
            'sub_cond_id' => $goods_id,
            'uid' => $user_id,
            'img' => empty($img) || !is_array($img)?'':implode(',',$img),
            'public' => $public,
            'level' => $level,
            'logistics' => $logistics,
            'service' => $service,
            'praise' => $praise,
        ]);
        $model->save();
    }


    //订单评论
    public static function comment(UserModel $user_model=null,array $input_data = [])
    {
        $order_id = $input_data['order_id']??0;
        $content = trim($input_data['content']??'');
        $tags = empty($input_data['tag'])|| !is_array($input_data['tag']) ? [] : $input_data['tag'];
        $img = empty($input_data['img'])|| !is_array($input_data['img']) ? '' : implode(',',$input_data['img']);
        $video = empty($input_data['video']) ? '' : $input_data['video'];
        $public = intval($input_data['public']??1);
        $public = $public==1 ? 1 : 2;
        $level = $input_data['level']??5;
        $level = $level > 5 || $level < 0 ? 5 : $level;
        $master_id = $input_data['master_id']??'';
        $cond_id = $input_data['cond_id']??'';
        $sub_cond_id = $input_data['sub_cond_id']??'';
        $cond_name = $input_data['cond_name']??'';
        if(!isset($input_data['ignore_order'])){ //订单
            if(empty($order_id)) throw new \Exception('参数异常:order_id');
            $model_order = OrderModel::where(['uid'=>$user_model['id'],'id'=>$order_id])->find();
            if(empty($model_order)) throw new \Exception('订单信息异常');
            if(!empty($model_order['is_comment'])) throw new \Exception("已评价");

            $master_id = $model_order['mid'];

            $model_order->is_comment = 1;
            $model_order->comment_time = time();
            $model_order->save();

            $model_order_goods = OrderGoodsModel::where(['oid'=>$model_order['id']])->find();
            $cond_id = $model_order_goods['gid'];
            $cond_name = $model_order_goods['sku_name'];
            //增加技师评论数量
            $masterUpdate=[];
            $masterUpdate['ser_comment_num'] = Db::raw('ser_comment_num + 1');
            if($level>3){
                $masterUpdate['ser_comment_nice_num'] = Db::raw('ser_comment_nice_num + 1');
            }
            MasterModel::where(['id'=>$model_order['mid']])->update($masterUpdate);
        }else{
            if(empty($sub_cond_id)) throw new \Exception('请填写商品id');
        }


        $model = new self();
        foreach ( self::$state_fields as $key => $item ) {

            $model->setAttr($key,in_array($key,$tags)?1:0);
        }


        $model->setAttrs([
            'master_id'=> $master_id,
            'uid'=>$user_model['id'],
            'public'=>$public,
            'img'=>empty($img)?null:$img,
            'video'=>empty($video)?null:$video,
            'level'=>$level,
            'content'=>$content,
            'cond_id'=>$cond_id,
            'sub_cond_id'=>$sub_cond_id,
            'cond_name'=>$cond_name,
        ]);
        $model->save();

    }

    //订单评论
    public static function orderGoodsComment(UserModel $user_model,array $input_data = [])
    {
        $cond_id = $input_data['cond_id']??'';
        $content = $input_data['content']??'';
        $level = $input_data['level']??5;
        $img = empty($input_data['img']) || !is_array($input_data['img']) ? [] : $input_data['img'];

        if(empty($cond_id)) throw new \Exception(Lang('err_order_comment_param',['param'=>'cond_id']));
        if(empty($content)) throw new \Exception(Lang('err_order_comment_content_empty'));
        $order_goods_model = OrderGoodsModel::find($cond_id);
        if(empty($order_goods_model)) throw new \Exception(Lang('err_order_comment_info_exist'));
        if($order_goods_model['comment_state']!=1) throw new \Exception(Lang('err_order_comment_has'));
        if($order_goods_model['uid']!=$user_model['id']) throw new \Exception(Lang('err_order_comment'));
        $save_data = [];
        $goods_id = $order_goods_model['gid']??'';
        $save_data[] = [
            'uid' => $user_model['id'],
            'cond_id' => $cond_id,
            'sub_cond_id' => $goods_id,
            'img' => empty($img)?null: implode(',',$img),
            'content' => $content,
            'cond_name' => $order_goods_model['sku_name'],
            'level' => $level,
        ];
        $order_goods_model->comment_state = 2;
        $order_goods_model->comment_time = date('Y-m-d H:i:s');
        $order_goods_model->save();

        $model = new self();
        $model->saveAll($save_data);

    }


    public static function getCount($id=0,$type=null)
    {
        $where = [];
        $where[] =['gid','=',$id];
        $where[] =['status','=',1];
        $whereFnc=null;
        if($type =='nice'){
            $where[] = ['level','>',3];
        }elseif($type=='bad'){
            $where[] = ['level','<=',3];
        }elseif($type=='img'){
            $whereFnc=function($query){
              $query->where([['img','<>',""]])->whereNotNull('img');
            };
        }elseif($type=='new'){ //近一个月的叫新评论
            $where[] = ['create_time','>',strtotime('-1 month',time())];
        }
        return self::where($where)->where($whereFnc)->count();
    }



    //商品评价信息
    public static function getCommentInfo(array $input_data = [])
    {

        $checkMode = trim($input_data['checkMode']??'');

        $where = [];
        if(isset($input_data['uid'])){
            $where[] = ['uid','=',$input_data['uid']];
        }



        if(isset($input_data['check_cond_id'])) {
            $where[] = ['cond_id','=',$input_data['check_cond_id']];
        }


        $where[] = ['status','=',1];

        $nice_per = $bad_per = 0;
        $count = $nice_count =$mind_count= $bad_count =0;
        $level_count = self::where($where)->group('level')->column('count(*) as num','level');
        $new_count = self::where($where)->where([
            ['create_time','>',strtotime('-1 month',time())]
        ])->count();
        //晒图
        $img_count = self::where($where)->whereRaw("(img is not null or video is not null)")->count();
        foreach ($level_count as $key=>$vo){
            $count+=$vo;
            if($key>=3){
                $nice_count+=$vo;
            }else{
                $bad_count+=$vo;
            }
        }

        if($count>0){
            $nice_per = (($nice_count/$count)*100);
        }

        if($count>0){
            $bad_per = (($bad_count/$count)*100);
        }

        $nice_per = sprintf('%d',$nice_per);
        $bad_per = sprintf('%d',$bad_per);

        return [
            'count'=>$count,
            'new_count'=>$new_count,
            'nice_per'=>$nice_per,
            'img_count'=>$img_count,
            'nice_count'=>$nice_count,
            'mind_count'=>$mind_count,
            'bad_count'=>$bad_count,
            'bad_per'=>$bad_per,
        ];
    }


    /**
     * 页面数据
     * @param array $input_data
     * @throws
     * @return \think\Paginator
     * */
    public static function getPageData(array $input_data = [])
    {
        $checkMode = trim($input_data['checkMode']??'');
        $keyword = trim($input_data['keyword']??'');
        $state_key = trim($input_data['state_key']??'');

        $limit = $input_data['limit']??null;
        $mode = $input_data['mode']??'';

        $where=[];
        $with_data = ['linkUser','linkOrderGoods'];
//        if(isset($input_data['check_praise_uid'])){
//            $check_praise_uid = $input_data['check_praise_uid'];
//            $with_data = array_merge($with_data,['linkPraise'=>function($query)use($check_praise_uid){
//                $query->where(['uid'=>$check_praise_uid]);
//            }]);
//        }
        $model = self::with($with_data);

        if(!empty($state_key) && array_key_exists($state_key, self::$state_fields)){ //状态查询
            $where[] = [$state_key,'=',1];
        }


        if($checkMode=='cond_id'){
            $check_cond_id = $input_data['check_cond_id']??'';
            if(empty($check_cond_id)){
                return Paginator::make(null,1,1,0);
            }
            $input_data['check_cond_id'] = $check_cond_id;
            unset($input_data['check_master_id']);
        }elseif($checkMode == 'master_id'){
            $check_master_id = $input_data['check_master_id']??'';
            if(empty($check_master_id)){
                return Paginator::make(null,1,1,0);
            }
            $input_data['check_master_id'] = $check_master_id;
            unset($input_data['check_cond_id']);
        }

        $keyword = trim($input_data['keyword']??'');
        !empty($keyword) && $where[] = ['content','like','%'.$keyword.'%'];
        $goods_name = trim($input_data['goods_name']??'');
        if(!empty($goods_name)){
            $all_goods_ids = GoodsModel::withTrashed()->where('name','like','%'.$goods_name.'%')->column('id');
            if(empty($all_goods_ids)){
                return Paginator::make([],1,1,0);
            }
            $where[] = ['sub_cond_id','in',$all_goods_ids];
        }




        if(isset($input_data['check_cond_id'])) {
            $where[] = ['cond_id','=',$input_data['check_cond_id']];
        }

        if(isset($input_data['check_type'])) {
            $where[] = ['type','=',$input_data['check_type']];
        }

        if(isset($input_data['check_sub_cond_id'])) {
            $where[] = ['sub_cond_id','=',$input_data['check_sub_cond_id']];
        }

        if(!empty($input_data['check_user_id'])) {
            $where[] = ['uid','=',$input_data['check_user_id']];
        }
        if(!empty($input_data['user_id'])) {
            $where[] = ['uid','=',$input_data['user_id']];
        }

        if(isset($input_data['uid'])) {
            $where[] = ['uid','=',$input_data['uid']];
        }

        if(isset($input_data['status'])) {
            $where[] = ['status','=',$input_data['status']];
        }

        //事件范围查询
        if(!empty($input_data['search_date']) && is_array($input_data['search_date']) && count($input_data['search_date'])==2){
            $input_data['start_date'] = $input_data['search_date'][0];
            $input_data['end_date'] = $input_data['search_date'][1];
        }
        //按时间查询
        $start_date = empty($input_data['start_date'])?'':trim($input_data['start_date']);
        $start_time = empty($start_date)?'':strtotime($start_date);
        $end_date = empty($input_data['end_date'])?'':trim($input_data['end_date']);
        $end__time = empty($end_date)?'':strtotime('+1 day',strtotime($end_date));
        if(!empty($start_time) && !empty($end__time)){
            $where[] = ['create_time','>=',$start_time];
            $where[] = ['create_time','<=',$end__time];
        }elseif(!empty($start_time)){
            $where[] = ['create_time','>=',$start_time];
        }elseif(!empty($end__time)){
            $where[] = ['create_time','<=',$end__time];
        }


        if($mode=='nice'){ //好评
            $where[] = ['level','>',2];
        }elseif($mode=='bad'){ //差评
            $where[] = ['level','<',3];
        }elseif($mode=='img'){ //晒图
            $model = $model->where(function($query){
                $query->where([['img','<>',""]])->whereNotNull('img');
            });
        }elseif($mode=='new'){ //新
            $where[] =['create_time','>',strtotime('-1 month')];
        }
//        dump($where,$input_data);exit;
        $all_ids = [];
        $paginate = $model->where($where)->order('id desc')->paginate($limit)->each(function($item)use(&$all_ids){
            $all_ids[] = $item['id'];
        });

        if(app()->http->getName()!='admin' && !empty($all_ids)){
            //增加浏览次数
            self::whereIn('id',$all_ids)->update([
                'views'=>Db::raw('views+1')
            ]);
        }

        return $paginate;
    }


    public static function orderComment(UserModel $user_model ,array $input_data = [])
    {
        $input_data['level'] = (empty($input_data['level']) || $input_data['level']>5 ||  $input_data['level']<0) ? 5 : $input_data['level'];
        $input_data['img'] = empty($input_data['img']) ?  '': (!is_array($input_data['img'])?$input_data['img']:implode(',',$input_data['img']));

        $input_data['type'] = empty($input_data['type'])?0:$input_data['type'];
        if(empty($input_data['cond_id']))  throw new \Exception('参数异常：cond_id');
        if(empty($input_data['content']) && empty($input_data['img']))  throw new \Exception('请输入评论内容');
        if($input_data['type']){

        }else{
            $cond_model = OrderGoodsModel::find($input_data['cond_id']);
            if(empty($cond_model))  throw new \Exception('评论对象不存在');
            if(!empty($cond_model['is_comment']))  throw new \Exception('您已评论');
            $input_data['sub_cond_id'] = $cond_model['gid']; //产品id
            $input_data['cond_name'] = $cond_model['sku_name'];
        }

        $model =new self();
        $model->setAttrs($input_data);
        $model->save();
        //保存评论状态
        $cond_model->setAttrs(['is_comment'=>1,'comment_date'=>date('Y-m-d H:i:s')]);
        $cond_model->save();

    }

    /**
     * @param array $input_data
     * @throws \Exception
     * @return self
     */
    public static function reply(MasterModel $model_master,array $input_data = [])
    {
        $id = $input_data['id']??0;
        $content = trim($input_data['content']??'');
        if(empty($content)) throw new \Exception('请输入回复内容');

        $model = self::find($id);
        if(empty($model)) throw new \Exception('评论不存在');
        if($model['master_id']!=$model_master['id']) throw new \Exception('无法回复该评论:-');
        if($model->reply_time > 0) throw new \Exception('无法再次回复');
        $model->setAttrs([
            'reply_content' => $content,
            'reply_time' => date('Y-m-d H:i:s'),
        ]);
        $model->save();


        return $model;
    }



    public static function selfDel(UserModel $user_model,array $input_data)
    {
        $comment_ids = empty($input_data['comment_ids']) ||!is_array($input_data['comment_ids']) ? [] : $input_data['comment_ids'];
        if(empty($comment_ids)) return;
        self::where(['uid'=>$user_model['id']])->whereIn('id',$comment_ids)->update(['delete_time'=>time()]);
    }

    public function apiFullInfo()
    {
        return array_merge($this->apiNormalInfo(),[
            'status' => $this['status'],
            'status_bool' => $this['status']==1,
        ]);
    }


    //评论基本信息
    public function apiNormalInfo()
    {
        $linkOrderGoods = $this->getRelation('linkOrderGoods');
        $user_info = $this->getRelation('linkUser');
        $public = $this['public'];
        $sku_name = $this->getAttr('sku_name');
        $reply_time = $this->getAttr('reply_time');
        return [
            'id' => $this->getAttr('id'),
            'content' => (string)$this->getAttr('content'),
            'reply_content' => (string)$this->getAttr('reply_content'),
            'reply_time' => empty($reply_time)?'':$reply_time,
            'sku_name' => empty($sku_name)?[]:explode(',',$sku_name),
            'level' => (Int)$this->getAttr('level'),
            'img' => $this->getAttr('img'),
            'video_img' => (string)$this->getAttr('video_img'),
            'video' => (string)$this->getAttr('video'),
            'views' => (int)$this->getAttr('views'),
            'praise_num' => (int)$this->getAttr('praise_num'),
            'create_time' => (string)$this->getAttr('create_time'),
            'project' => empty($linkProject)?(object)[]:$linkProject->apiNormalInfo(),
//            'is_praise' => empty($linkPraise['handle_time']) ? 0 : 1,

            'uid' => $this->getAttr('uid'),
            'user_name' => $public==2 ? '匿名评论' : (empty($user_info) ? '' : $user_info['name']),
            'user_face' => empty($user_info) ? '' : $user_info['avatar'],

            'goods_info' => empty($linkOrderGoods)?[]: $linkOrderGoods->apiNormalInfo(),
        ];
    }

    public function linkOrderGoods()
    {
        return $this->belongsTo(OrderGoodsModel::class,'cond_id');
    }
    public function linkMaster()
    {
        return $this->belongsTo(MasterModel::class,'master_id');
    }
    public function linkUser()
    {
        return $this->belongsTo(UserModel::class,'uid');
    }

    public function linkProject()
    {
        return $this->belongsTo(ProProjectModel::class,'cond_id');
    }

    public function linkPraise()
    {
        return $this->hasOne(CommentPraiseModel::class,'cid');
    }


}